import useUserStore from '@/store/user'
import { jump } from '@/utils/router'
import { toast } from '@/utils/uni-app'
import { getInfo } from '@/api/user'
import { computed } from 'vue'

/**
 * 登录校验，未登录跳转登录流程并返回 false，已登录返回 true
 * @param {Boolean} showToast - 是否提示登录
 * @param {Boolean} isJump - 是否跳转登录页面
 * @returns {Boolean} true=已登录, false=未登录
 */
export const useAuth = (options) => {
  const { showToast = true, isJump = true } = options || {}
  const { token } = useUserStore()

  if (!token) {
    showToast && toast('请先登陆')

    const url = '/pages/user/login/index'
    setTimeout(() => isJump && jump(url), 600)

    return false
  }

  return true
}

export const useUserInfo = () => {
  const userStore = useUserStore()

  if (userStore.token) {
    getInfo(null, true)
      .then(res => userStore.updateInfo(res))
      .catch(err => console.log(err))
  }

  return computed(() => userStore.info)
}
